using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Services;

namespace WinformDevFramework
{
    public partial class Frmw_OtherInWarehouse : BaseForm1
    {
        private Iw_OtherInWarehouseServices _w_OtherInWarehouseServices;
        private Iw_OtherInWarehouseDetailServices _wOtherInWarehouseDetailServices;
        private Iw_Warehouseervices _warehoursesServices;
        private IW_GoodsServices _wGoodsServices;
        private IsysDicDataServices _sysDicDataServices;
        private ISysUserServices _sysUserServices;
        public Frmw_OtherInWarehouse(Iw_OtherInWarehouseServices w_OtherInWarehouseServices, Iw_OtherInWarehouseDetailServices wOtherInWarehouseDetailServices, Iw_Warehouseervices warehoursesServices, IW_GoodsServices wGoodsServices, IsysDicDataServices sysDicDataServices, ISysUserServices sysUserServices)
        {
            _w_OtherInWarehouseServices = w_OtherInWarehouseServices;
            InitializeComponent();
            _wOtherInWarehouseDetailServices = wOtherInWarehouseDetailServices;
            _warehoursesServices = warehoursesServices;
            _wGoodsServices = wGoodsServices;
            _sysDicDataServices = sysDicDataServices;
            _sysUserServices = sysUserServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["TypeCode"].HeaderText = "业务类别";
            this.dataGridViewList.Columns["InvoicesDate"].HeaderText = "单据日期";
            this.dataGridViewList.Columns["OtherInWarehouseCode"].HeaderText = "入库单号";
            this.dataGridViewList.Columns["InvoicesImage"].Visible = false;
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["Status"].Visible = false;
            this.dataGridViewList.Columns["MakeUserID"].Visible = false;
            //设置明细 仓库
            Warehouse.DataSource = _warehoursesServices.Query();
            Warehouse.DisplayMember = "WarehouseName";
            Warehouse.ValueMember = "WarehouseCode";

            GoodsName.DataSource = _wGoodsServices.Query();
            GoodsName.DisplayMember = "GoodsName";
            GoodsName.ValueMember = "GoodsCode";

            MakeUser.DataSource = _sysUserServices.Query();//值查找销售部门
            MakeUser.ValueMember = "ID";
            MakeUser.DisplayMember = "Fullname";
            TypeCode.DataSource = _sysDicDataServices.QueryListByClause(p => p.DicTypeID == 2003);
            TypeCode.DisplayMember = "DicData";
            TypeCode.ValueMember = "ID";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_OtherInWarehouse;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.TypeCode.SelectedValue = model.TypeCode.ToInt32();
            this.InvoicesDate.Text = model.InvoicesDate.ToString();
            this.OtherInWarehouseCode.Text = model.OtherInWarehouseCode;
            this.InvoicesImage.Text = model.InvoicesImage;
            this.Remark.Text = model.Remark;
            this.Status.Text = model.Status;
            this.MakeUser.SelectedValue = model.MakeUserID;

            SetDataToDetail(GetDetailData(OtherInWarehouseCode.Text));

            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SetDataGridViewReadonlyStatus();
            MakeUser.SelectedValue = AppInfo.User.ID;
            dataGridViewDetail.Rows.Clear();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SetDataGridViewReadonlyStatus();
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_OtherInWarehouse model = new w_OtherInWarehouse();
                    // TODO获取界面的数据
                    model.TypeCode = this.TypeCode.SelectedValue.ToString();
                    model.InvoicesDate = this.InvoicesDate.Value.ToDateTime();
                    if (string.IsNullOrEmpty(this.OtherInWarehouseCode.Text))
                    {
                        model.OtherInWarehouseCode = $"QTRK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.OtherInWarehouseCode = this.OtherInWarehouseCode.Text;
                    }
                    model.InvoicesImage = this.InvoicesImage.Text;
                    model.Remark = this.Remark.Text;
                    model.Status = this.Status.Text;
                    model.MakeUserID = this.MakeUser.SelectedValue.ToInt32();


                    #region 明细表

                    List<w_OtherInWarehouseDetail> dataDetails = new List<w_OtherInWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_OtherInWarehouseDetail detail = new w_OtherInWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["Warehouse"].Value?.ToString();
                            detail.WarehouseName = row.Cells["Warehouse"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].Value.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    #endregion
                    int id = _w_OtherInWarehouseServices.AddOtherInWarehouseInfo(model, dataDetails);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        OtherInWarehouseCode.Text = model.OtherInWarehouseCode;
                        SetDataToDetail(GetDetailData(model.OtherInWarehouseCode));
                    }
                }
                // 修改
                else
                {
                    w_OtherInWarehouse model = _w_OtherInWarehouseServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.TypeCode = this.TypeCode.SelectedValue.ToString();
                    model.InvoicesDate = this.InvoicesDate.Value.ToDateTime();
                    model.OtherInWarehouseCode = this.OtherInWarehouseCode.Text;
                    model.InvoicesImage = this.InvoicesImage.Text;
                    model.Remark = this.Remark.Text;
                    model.Status = this.Status.Text;
                    model.MakeUserID = this.MakeUser.SelectedValue.ToInt32();

                    #region 明细表

                    List<w_OtherInWarehouseDetail> dataDetails = new List<w_OtherInWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_OtherInWarehouseDetail detail = new w_OtherInWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].Value.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["Warehouse"].Value.ToString();
                            detail.WarehouseName = row.Cells["Warehouse"].FormattedValue.ToString();
                            detail.OtherInWarehouseDetailCode = row.Cells["OtherInWarehouseDetailCode"].FormattedValue.ToString();

                            detail.OtherInWarehouseCode = row.Cells["OtherInWarehouseCodeD"].FormattedValue.ToString();

                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    #endregion
                    if (_w_OtherInWarehouseServices.UpdateOtherInWarehouseInfo(model, dataDetails))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.OtherInWarehouseCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            SetDataToDetail(GetDetailData(OtherInWarehouseCode.Text));
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                if (_w_OtherInWarehouseServices.DeleteOtherInWarehouseInfo(new w_OtherInWarehouse()
                {
                    ID = txtID.Text.ToInt32(),
                    OtherInWarehouseCode = OtherInWarehouseCode.Text
                }))
                {
                    formStatus = FormStatus.Del;
                    SetToolButtonStatus(formStatus);
                    //列表重新赋值
                    dataGridViewDetail.Rows.Clear();
                    this.dataGridViewList.DataSource = GetData();
                }

            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_OtherInWarehouse> GetData()
        {
            List<w_OtherInWarehouse> data = new List<w_OtherInWarehouse>();
            data = _w_OtherInWarehouseServices.Query();
            return data;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
        ///// <summary>
        ///// 明细表 设置数据 --采购单号带出
        ///// </summary>
        ///// <param name="details"></param>
        //private void SetDataToDetail(List<w_BuyDetail> details)
        //{
        //    dataGridViewDetail.Rows.Clear();
        //    details.ForEach(p =>
        //    {
        //        dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
        //        DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
        //        row.Cells["BuyCodeD"].Value = p.BuyCode;
        //        row.Cells["GoodsName"].Value = p.GoodsName;
        //        row.Cells["GoodsCode"].Value = p.GoodsCode;
        //        row.Cells["Warehouse"].Value = "CK001";
        //        //row.Cells["GoodsSpec"].Value = p.GoodsCode;
        //        //row.Cells["GoodsUnit"].Value = p.GoodsCode;
        //        row.Cells["Number"].Value = 0;
        //        row.Cells["RemarkD"].Value = p.Remark;

        //        //row.Cells["BuyID"].Value = p.BuyID;
        //        //row.Cells["BuyCodeD"].Value = p.BuyCode;
        //        //row.Cells["BuyDetailCode"].Value = p.BuyDetailCode;
        //    });
        //}
        /// <summary>
        /// 明细表 设置数据 --主表带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_OtherInWarehouseDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["GoodsName"].Value = p.GoodsCode;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = p.Number;
                row.Cells["RemarkD"].Value = p.Remark;
                row.Cells["Warehouse"].Value = p.WarehouseCode;
                row.Cells["OtherInWarehouseDetailCode"].Value = p.OtherInWarehouseDetailCode;
                row.Cells["OtherInWarehouseCodeD"].Value = p.OtherInWarehouseCode;
            });
        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_OtherInWarehouseDetail> GetDetailData(string code)
        {
            List<w_OtherInWarehouseDetail> data = new List<w_OtherInWarehouseDetail>();
            data = _wOtherInWarehouseDetailServices.QueryListByClause(p => p.OtherInWarehouseCode == code);
            return data;
        }

        private void dataGridViewDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "Number", "Warehouse", "RemarkD", "GoodsName" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }

        private void dataGridViewDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (dataGridViewDetail.Columns[e.ColumnIndex].Name == "GoodsName" && !string.IsNullOrEmpty(dataGridViewDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString()))
                {

                    dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsCode"].Value = dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsName"].Value;
                    var code = dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsName"].Value.ToString();
                    var goods = _wGoodsServices.QueryByClause(p =>
                        p.GoodsCode == code);
                    if (goods != null)
                    {
                        dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsUnit"].Value = goods.GoodsUnit;
                        dataGridViewDetail.Rows[e.RowIndex].Cells["GoodsSpec"].Value = goods.GoodsSpec;
                    }
                }
            }
        }
    }
}
